package org.bioversityinternational.mgbms.notify;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.log4j.Logger;

import org.bioversityinternational.mgbms.model.dao.OrderStatusDao;
import org.bioversityinternational.mgbms.model.domain.Contact;
import org.bioversityinternational.mgbms.model.domain.Login;
import org.bioversityinternational.mgbms.model.domain.Order;
import org.bioversityinternational.mgbms.text.Helper;
import org.bioversityinternational.mgbms.text.TextConstants;
import org.bioversityinternational.mgbms.ws.impl.MgbmsServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;

public class EmailNotifier
{
	static private final Logger LOG = Logger.getLogger(EmailNotifier.class);

	@Autowired MgbmsServiceImpl service;
	
	private JavaMailSenderImpl mailSender;
	
	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}
	
	public void notifyNewPassword(Login user, boolean fForAccountCreation) throws MessagingException, UnsupportedEncodingException
	{
		String sHTMLBody = "<html><head></head><body><p>";
		sHTMLBody += TextConstants.get("EmailNotifier.user.passwordNotification.email.body") + user.getPassword();
		sHTMLBody += "</p></body></html>";
		
		MimeMessage message = createMultipartMessage(sHTMLBody);
		message.setSubject(TextConstants.get(fForAccountCreation ? "EmailNotifier.user.subscription.email.subject" : "EmailNotifier.user.passwordRenewal.email.subject"), "UTF-8");

		message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getContact().getEmail()));
		
		message.saveChanges();

		mailSender.send(message);
	}
	
	public void notifyNewOrderRequest(Order order) throws MessagingException, UnsupportedEncodingException
	{
		Contact orderRecipient = order.getContact();
		
		String sHTMLBody = "<html><head></head><body><p>";
		sHTMLBody += TextConstants.get("EmailNotifier.order.requestSubmitted.body") + "<br><br>" + Helper.nullToBlank(order.getContact().getTitle(), " ") + order.getContact().getLastName() + " " + order.getContact().getFirstName() + "<br><br><blockquote><pre>" + Helper.compileAddress(orderRecipient.getAddress()) + "</pre></blockquote><br><br>";
		sHTMLBody += "</p><p>";
		if (order.getOrderStatus().getId() != OrderStatusDao.ORDER_STATUS_CANCELLED)
			for (String smtaDoc : service.getSMTA(order.getId()))
				sHTMLBody += smtaDoc + "<br>";
		else
			sHTMLBody += TextConstants.get("EmailNotifier.order.requestSubmitted.invalidPurpose") + " " + order.getStudypurpose();
		sHTMLBody += "</p></body></html>";
		
		MimeMessage message = createMultipartMessage(sHTMLBody);
		message.setSubject(TextConstants.get("EmailNotifier.order.requestSubmitted.subject") + " " + order.getId() + " (" + order.getContact().getEmail() + ")", "UTF-8");
		
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(TextConstants.get("EmailNotifier.system.adminEmailAddress")));
		
		message.saveChanges();

		mailSender.send(message);
	}
	
	private MimeMessage createMultipartMessage(String sHTMLBody) throws MessagingException, UnsupportedEncodingException
	{
		String encodedBody = MimeUtility.encodeText(sHTMLBody);
		
		MimeMessage message = mailSender.createMimeMessage();
		MimeMultipart multipart = new MimeMultipart("alternative");
		MimeBodyPart messageHtmlBody = new MimeBodyPart();
		MimeBodyPart messageTxtBody = new MimeBodyPart();
		
		messageHtmlBody.setContent(encodedBody, "text/html");
		multipart.addBodyPart(messageHtmlBody);
		
		messageTxtBody.setContent(Helper.stripHTML(encodedBody.replaceAll("<br>", "\r\n")), "text/plain");
		multipart.addBodyPart(messageTxtBody);
		
		message.setContent(multipart);
		message.setSentDate(new java.util.Date());
		message.addFrom(new InternetAddress[] {new InternetAddress(TextConstants.get("EmailNotifier.system.emailSenderAddress"))});

		return message;
	}

	public void sendRegistrationCode(String sUserEmail, String sRegCode, boolean fUserFound) throws MessagingException, UnsupportedEncodingException
	{
		String sHTMLBody = "<html><head></head><body>";
		sHTMLBody += "<p>" + TextConstants.get("EmailNotifier.user.registrationCodeNotification.email.body") + ":<br><br>" + sRegCode + "</p><br><br>";
		if (fUserFound)
			sHTMLBody += "<p>(" + TextConstants.get("EmailNotifier.user.registrationCodeNotification.email.body.userRecordFound") + ")</p>";
		sHTMLBody += "</body></html>";
		
		MimeMessage message = createMultipartMessage(sHTMLBody);
		message.setSubject(MimeUtility.encodeText(TextConstants.get("EmailNotifier.user.registrationCodeNotification.email.subject")));
		
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(sUserEmail));
		
		message.saveChanges();

		mailSender.send(message);
	}

}
